package com.gitee.wsl.ext.array.bytes

import com.gitee.wsl.ext.array.emptyByteArray
import com.gitee.wsl.io.buffer.ByteBuffer
import com.gitee.wsl.io.buffer.buffered
import com.gitee.wsl.io.buffer.readContent
import com.gitee.wsl.lang.ByteOrder


/**
 * Creates a byte array from given short array.
 * The resulting byte array will have length shortArray * 2.
 *
 *
 *
 * **Analysis**
 *
 *  * Time Complexity: `O(n)`
 *  * Space Complexity: `O(n)`
 *  * Alters Parameters: `false`
 *
 *
 *
 * @param shortArray to convert
 * @return resulting byte array
 */
fun ShortArray.toByteArray(byteOrder: ByteOrder=ByteOrder.BigEndian): ByteArray {
    if(isEmpty()) return emptyByteArray

    val buffer: ByteBuffer = ByteBuffer.allocate(size * 2,byteOrder)
    for (i in indices) {
        buffer.short = this[i]
    }
    return buffer.contentBytes
}

fun ByteArray.toShortArray(byteOrder: ByteOrder=ByteOrder.BigEndian): ShortArray{
    val list = mutableListOf<Short>()
    this.buffered(byteOrder).readContent { list.add(short) }
    return list.toShortArray()
}